package vip.xiaonuo.modular.manage.bioperateddata.Listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.modular.gaode.CoordinateConvertAddr;
import vip.xiaonuo.modular.gaode.LngLat;
import vip.xiaonuo.modular.manage.bioperateddata.entity.BiOperatedData;
import vip.xiaonuo.modular.manage.bioperateddata.service.BiOperatedDataService;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BiOperatedDataListener extends AnalysisEventListener<BiOperatedData> {

    private final static int MAX_LIST_SIZE = 50;

    private List<BiOperatedData> operatedData = new ArrayList<>(MAX_LIST_SIZE);

    private BiOperatedDataService biOperatedDataService;

    private String orgCode;

    //手动传入service对象
    public BiOperatedDataListener(BiOperatedDataService biOperatedDataService , String orgCode) {
        this.biOperatedDataService = biOperatedDataService;
        this.orgCode = orgCode;
    }




    // 每解析一行数据,该方法会被调用一次
    @Override
    public void invoke(BiOperatedData biOperatedData, AnalysisContext analysisContext) {
        if (StringUtils.isNotBlank(biOperatedData.getLat()) && StringUtils.isNotBlank(biOperatedData.getLng())){
//            逆地理编码获取省市区
            String[] batchLocationAddr = CoordinateConvertAddr.getBatchLocationAddr(biOperatedData.getLng() + "," + biOperatedData.getLat());
            biOperatedData.setProvName(batchLocationAddr[2]);
            biOperatedData.setCityName(batchLocationAddr[3]);
            biOperatedData.setCountryName(batchLocationAddr[4]);
        }else{
//            地理编码获取省市区
            LngLat batchLngLatAddr = CoordinateConvertAddr.getBatchLngLatAddr(biOperatedData.getAddress());
            biOperatedData.setLng(batchLngLatAddr.getLongitude());
            biOperatedData.setLat(batchLngLatAddr.getLatitude());
            biOperatedData.setProvName(batchLngLatAddr.getProvName());
            biOperatedData.setCityName(batchLngLatAddr.getCityName());
            biOperatedData.setCountryName(batchLngLatAddr.getCoutryName());
        }
        if (StringUtils.isNotBlank(orgCode)){
            biOperatedData.setOrgCode(orgCode);
        }
        operatedData.add(biOperatedData);
        if (operatedData.size() == MAX_LIST_SIZE){
            biOperatedDataService.saveBatch(operatedData);
            operatedData = new ArrayList<>(MAX_LIST_SIZE);
        }
    }
    // 全部解析完成被调用
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (operatedData.size() > 0){
            biOperatedDataService.saveBatch(operatedData);
        }
        log.info("解析完成...");
        // 可以将解析的数据保存到数据库
    }
}
